package com.lagou.base;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.util.Map;

public class BaseServlet extends HttpServlet {

    /*
     * doGET方法作为一个调度器 .根据请求功能的不同,调用对应的方法
     *      规定必须传递一个参数
     *           methodName=功能名
     * */

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.获取参数 要访问的方法名
        String methodName = null;
        String contentType = req.getHeader("Content-Type");

        //判断传递的数据是否json格式
        if("application/json".equals(contentType)){
            //json格式，调用getpostjson
            String postJSON = getPostJSON(req);

            //将json格式的字符串转化为map
            Map<String,Object> map = JSON.parseObject(postJSON,Map.class);

            //从map集合中获取methodName
            methodName = (String) map.get("methodName");

            //将流中获取的数据保存到request域对象中
            req.setAttribute("map",map);
        }else{
            methodName = req.getParameter("methodName");
        }
        //2.业务处理，通过反射优化代码，提高代码的可维护性
        if (methodName != null) {
            //1.获取字节码对象
            Class c = this.getClass();

            //2.根据传入的方法名，获取对应方法对象再执行方法
            Method method = null;
            try {
                method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

            //3.调用Method对象的invoke方法，执行对应的功能
            try {
                method.invoke(this, req, resp);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public String getPostJSON(HttpServletRequest req){
        try {
            //1.从request中获取字符缓冲输入流对象
            BufferedReader reader = req.getReader();
            //2.创建StringBuffer,用来保存读取出来的数据
            StringBuffer stringBuffer = new StringBuffer();
            //3.循环读取
            String line = null;
            while ((line = reader.readLine()) != null){
                stringBuffer.append(line);
            }
            //4.将读取到的内容转行为字符串然后返回
            return stringBuffer.toString();
        } catch (IOException e) {

            return null;
        }
    }

}
